package cppcloud

import "sync"

// handleMapType 线程安全的消息映射处理map
type messageHandleValue struct {
	hand *MessageHandle
	once bool
}

type handleMapType struct {
	mp map[uint32]messageHandleValue
	locker *sync.Mutex
}

func createHandleMap() *handleMapType {
	return &handleMapType{make(map[uint32]messageHandleValue), new(sync.Mutex)}
}

// 读取map key对应值
func (handmp *handleMapType) get(key uint32) (*MessageHandle, bool) {
	handmp.locker.Lock()
	defer handmp.locker.Unlock()
	if val, ok := handmp.mp[key]; ok {
		return val.hand, val.once
	}
	return nil, false
}

func (handmp *handleMapType) set(key uint32, ptr *MessageHandle, once bool) {
	handmp.locker.Lock()
	defer handmp.locker.Unlock()

	if nil == ptr { // 删除
		delete(handmp.mp, key)
	} else { // 添加
		handmp.mp[key] = messageHandleValue{ptr, once}
	}
}

